/**
 * how to use
 *
 *

 api
 .invoke("POST", `/api/v1/has-permission`, {
    actions: [
      {
        id: "createBucket",
        action: "s3:CreateBucket",
      },
    ],
  })
 .then(
 )
 .catch((err: any) => {

        });
 *
 */

import request, { Request, ResponseError } from "superagent";
import prefix from "superagent-prefix";

// import { clearSession, getToken } from "/@/utils/auth";
// import { Notify, Toast } from "vant";
// import router from "/@/router";
// import { i18n } from "/@/locales/createI18nOptions";
// import { isEnPage } from "/@/utils/env";

const baseURL = "/api-v1";

export class API {
  invoke<T = any>(method: string, url: string, data?: any): Promise<T> {
    return (
      request(method, url)
        // 接口公共前缀
        .use(prefix(baseURL))

        // .set("Authorization", `Bearer ${getToken()}`)
        // .set("lang", isEnPage() ? "en" : "cn")
        .send(data)
        .timeout({
          response: 15 * 1000,
          deadline: 15 * 1000,
        })
        .then((res) => {
          const body: T = res.body;

          return body;
        })
        .catch((err: ResponseError) => {
          if (err.status === 401) {
            // 接口http状态码 401  特殊处理
          }

          return this.onError(err);
        })
    );
  }

  onError(err: ResponseError) {
    if (err.status) {
      // 401以外的错误
      return Promise.reject(err);
    } else {
      // 超时
    }
  }
}

const api = new API();
export default api;
